package com.yun.zf.admin.controller;

import com.yun.zf.common.app.domain.ZfCity;
import com.yun.zf.common.constant.PactConstants;
import com.yun.zf.common.utils.DateUtils;
import com.yun.zf.common.vo.Response;
import com.yun.zf.system.exception.CustomException;
import com.yun.zf.system.security.utils.SecurityUtils;
import com.yun.zf.system.service.ISysDictDataService;
import com.yun.zf.system.service.PermissionService;
import com.yun.zf.system.service.ZfCityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * web层通用数据处理
 * 
 * @author ruoyi
 */
@Slf4j
public class BaseController
{

    @Autowired
     private ISysDictDataService dictDataService;
    @Autowired
     private PermissionService permissionService;
    @Autowired
    private ZfCityService cityService;

    // 城市处理
    Long  aCode= null;
    Long prov=null;
    int agentNo=-1;
    @InitBinder
    public void initBinder(WebDataBinder binder, HttpServletRequest request)
    {

        String dvalue = dictDataService.getValue(PactConstants.MANAGER, PactConstants.MANAGER_KEY);
        // 验证登录用户是否为公司客户人员或者管理员，如果是公司管理员用户则需要使用带入的城市，如果不是则使用登录业务员所在城市
        Boolean flage = permissionService.hasAnyRoles(dvalue);
        if (flage){
            String city = request.getHeader("city");
            log.info("头部携带城市信息---------{}",city);
            if (StringUtils.isBlank(city)){
                throw  new CustomException("管理员用户请选择城市后在进行操作");
            }
            aCode = Long.parseLong(request.getHeader("city")) ;
            // 获取省份代码
         ZfCity zfCity = cityService.getCity(aCode);
         prov= zfCity.getPid();
        }else {
            // 当前业务员城市 和省份
            aCode = Long.parseLong(SecurityUtils.getLoginUser().getCityCode());
            prov = Long.parseLong(SecurityUtils.getLoginUser().getProvinceCode());
            agentNo = SecurityUtils.getLoginUser().getAgentNo();
            if (agentNo==0){
                throw  new CustomException("业务员工号不存在");
            }
        }
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
        {
            @Override
            public void setAsText(String text)
            {
                setValue(DateUtils.parseDate(text));
            }
        });
    }




    /**
     * 响应返回结果
     * 
     * @param rows 影响行数
     * @return 操作结果
     */
    protected Response toAjax(int rows)
    {
        return rows > 0 ? Response.success() : Response.error();
    }
}
